package com.block.datapush.service.apipush;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XiaoXiongQianBaoRateUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 小熊钱包-分润  双授权
 */
@Service
public class XiaoXiongQianBaoSsqRatePushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String channelCode = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phoneMd5", memberSourceInfo.getMobileMd5().toLowerCase());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("gender", XiaoXiongQianBaoRateUtil.getSex(memberSourceInfo.getSex()));
        bizMap.put("education", XiaoXiongQianBaoRateUtil.getEducation(memberSourceInfo.getXueli()));
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("zhima", XiaoXiongQianBaoRateUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("gongjijin", XiaoXiongQianBaoRateUtil.getGongJiJin(memberSourceInfo.getGjj()));
        bizMap.put("shebao", XiaoXiongQianBaoRateUtil.getSheBao(memberSourceInfo.getShebao()));
        bizMap.put("profession", XiaoXiongQianBaoRateUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("client", 1);
        bizMap.put("income", XiaoXiongQianBaoRateUtil.getShouru(memberSourceInfo.getShouru()));
        bizMap.put("house", XiaoXiongQianBaoRateUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", XiaoXiongQianBaoRateUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", XiaoXiongQianBaoRateUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("payoff", 1);
        bizMap.put("loanAmount", XiaoXiongQianBaoRateUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", XiaoXiongQianBaoRateUtil.getloanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("purpose", XiaoXiongQianBaoRateUtil.getYongTu(memberSourceInfo.getYongtu()));
        bizMap.put("creditCard", XiaoXiongQianBaoRateUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("huabei", XiaoXiongQianBaoRateUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao", XiaoXiongQianBaoRateUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("weilidai", 0);
        bizMap.put("ip", XiaoXiongQianBaoRateUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("credit", XiaoXiongQianBaoRateUtil.getYuQi(memberSourceInfo.getYuqi()));

        //当前时间
        String requestTime = String.valueOf(System.currentTimeMillis() / 1000);

        String content = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSONObject.toJSONString(bizMap));


        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("channelCode", channelCode);
        paramMap.put("requestId", UUID.randomUUID().toString());
        paramMap.put("content", content);
        paramMap.put("requestTime", requestTime);


        log.info("【小熊钱包(分润)下游双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);


        log.info("【小熊钱包(分润)下游双授权】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (code == 200) {
            JSONObject data = resultObject.getJSONObject("data");
            String applyNo = data.getString("applyNo");
            String logo = data.getString("productLogo");
            String companyName = data.getString("companyName");
            String productName = data.getString("productName");
            JSONArray protocoList = data.getJSONArray("protocolList");

            // 撞库成功之后，商户的机构数据存储

            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo", applyNo);
            infoObject.put("productId", applyNo);
            infoObject.put("productName", productName);
            infoObject.put("companyName", companyName);
            infoObject.put("companyLogo", logo);
            infoObject.put("maxLoanAmount", "200000");
            infoObject.put("maxLoanRate", "7");
            infoObject.put("minLoanRate", "1");
            infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            for (int i = 0;i<protocoList.size();i++){
                JSONObject jsonObject = protocoList.getJSONObject(i);
                JSONObject jsonObject1 = new JSONObject();
                String name = jsonObject.getString("protocolName");
                String url = jsonObject.getString("protocolUrl");
                jsonObject1.put("protocalName",name);
                jsonObject1.put("protocalUrl",url);
                jsonArray.add(jsonObject1);
            }
            infoObject.put("protocalList", jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                String priceRate = data.getString("price");
                if (StringUtils.isEmpty(priceRate)){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal bigDecimal = new BigDecimal(priceRate);//下游返回分润后价格
                if (bigDecimal.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal dividePrice = bigDecimal.divide(typeRate);//分润前价格
                pushApiResult.setPrice(dividePrice);
                pushApiResult.setPriceRight(bigDecimal);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save) {
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(applyNo);
                extJson.put("applyNo", applyNo);
            } else {
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String applyNo = extJson.getString("applyNo");

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String channelCode = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobile", memberSourceInfo.getMobile());
        bizMap.put("realName", memberSourceInfo.getRealname());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("gender", XiaoXiongQianBaoRateUtil.getSex(memberSourceInfo.getSex()));
        bizMap.put("education", XiaoXiongQianBaoRateUtil.getEducation(memberSourceInfo.getXueli()));
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("zhima", XiaoXiongQianBaoRateUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("gongjijin", XiaoXiongQianBaoRateUtil.getGongJiJin(memberSourceInfo.getGjj()));
        bizMap.put("shebao", XiaoXiongQianBaoRateUtil.getSheBao(memberSourceInfo.getShebao()));
        bizMap.put("profession", XiaoXiongQianBaoRateUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("client", 1);
        bizMap.put("income", XiaoXiongQianBaoRateUtil.getShouru(memberSourceInfo.getShouru()));
        bizMap.put("house", XiaoXiongQianBaoRateUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", XiaoXiongQianBaoRateUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", XiaoXiongQianBaoRateUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("payoff", 1);
        bizMap.put("loanAmount", XiaoXiongQianBaoRateUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", XiaoXiongQianBaoRateUtil.getloanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("purpose", XiaoXiongQianBaoRateUtil.getYongTu(memberSourceInfo.getYongtu()));
        bizMap.put("creditCard", XiaoXiongQianBaoRateUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("huabei", XiaoXiongQianBaoRateUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao", XiaoXiongQianBaoRateUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("weilidai", 0);
        bizMap.put("ip", XiaoXiongQianBaoRateUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("applyNo", applyNo);

        //当前时间
        String requestTime = String.valueOf(System.currentTimeMillis() / 1000);

        String content = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSONObject.toJSONString(bizMap));


        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("channelCode", channelCode);
        paramMap.put("requestId", UUID.randomUUID().toString());
        paramMap.put("content", content);
        paramMap.put("requestTime", requestTime);

        log.info("【小熊钱包(分润)下游双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【小熊钱包(分润)下游双授权】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 200) {
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 200) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }



}
